#!/usr/bin/env bash

notify() {
	notify-send -t 3000 "$1"
}

dir="$HOME/.config/clash"

cd $dir

mkdir -p $dir/history

if [[ "$1" == "l" ]]; then
	subscribe="$dir/subscribe-long-term.uri"
	config="$dir/history/config-long-term-`date \"+%Y-%m-%d-%H:%M:%S\"`.yaml"
else
	subscribe="$dir/subscribe-monthly.uri"
	config="$dir/history/config-monthly-`date \"+%Y-%m-%d-%H:%M:%S\"`.yaml"
fi

log="$dir/clash.log"

dest="Emo"

rm -f $dir/$dest

notify "开始下载"

aria2c -d "$dir" -o $dest -i $subscribe

[[ $? -eq 0 ]] || {
    echo "[`date`] Failed to download new subscribe file." >> $log
	notify "更新失败"
    exit 1
}

[[ -f ./${dest} ]] && {
    echo "socks-port: 7891" > $config
    cat $dir/$dest >> $config
    cat ${config} > ${dir}/config.yaml

    killall -q clash
    clash &
	rm -f ./$dest

	notify "更新成功"

    exit 0
} || {
    echo "[`date`]Cannot find subscribe file." >> $log
    exit 1
}
